#ifndef EVENT_DISPATCHER_H
#define EVENT_DISPATCHER_H

#include "Common.h"
#include "EpollDispatcherData.h"
#include <assert.h>
#include "Channel.h"
// #include "EventLoop.h"

// class Channel;
class ChannelMap;
class EventLoop;

class EventDispatcher {

public:

	int add(EpollDispatcherData *data, Channel *channel) const {

		int fd = channel->fd;
		int events = 0;

		if (channel->events & EVENT_READ) {
			events = events | EPOLLIN;
		}

		if (channel->events & EVENT_WRITE) {
			events = events | EPOLLOUT;			
		}

		struct epoll_event event;
    	event.data.fd = fd;
    	event.events = events;
		//    event.events = events | EPOLLET;
    	if (epoll_ctl(data->efd, EPOLL_CTL_ADD, fd, &event) == -1) {
        	printf("epoll_ctl add  fd failed\n");
    	}

    	return 0;
	}


	int del(EpollDispatcherData *data, Channel *channel) const {
		int fd = channel->fd;
		
		int events = 0;

		if (channel->events & EVENT_READ) {
			events = events | EPOLLIN;
		}

		if (channel->events & EVENT_WRITE) {
			events = events | EPOLLOUT;			
		}

		struct epoll_event event;
    	event.data.fd = fd;
    	event.events = events;
    	if (epoll_ctl(data->efd, EPOLL_CTL_DEL, fd, &event) == -1) {
        	printf("epoll_ctl add  fd failed\n");
    	}

    	return 0;
	}

	int update(EpollDispatcherData *data, Channel *channel) const {
		int fd = channel->fd;
		int events = 0;

		if (channel->events & EVENT_READ) {
			events = events | EPOLLIN;
		}

		if (channel->events & EVENT_WRITE) {
			events = events | EPOLLOUT;			
		}

		struct epoll_event event;
    	event.data.fd = fd;
    	event.events = events;

    	if (epoll_ctl(data->efd, EPOLL_CTL_MOD, fd, &event) == -1) {
        	// error(1, errno, "epoll_ctl add  fd failed");
        	printf("epoll_ctl add  fd failed\n");
    	}

    	return 0;

	}

	int dispatch_loop(EventLoop *loop, struct timeval *timeval) const;


	void clear(void) {
		return;
	}

};


#endif
